package com.net.xpay.partner.controller.partner;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.net.common.model.ResultData;
import com.net.common.model.ResultPagedList;
import com.net.common.util.LocalDateUtil;
import com.net.common.util.SerializationUtil;
import com.net.xpay.common.domain.partner.Partner;
import com.net.xpay.common.domain.partner.PartnerWithdrawRecord;
import com.net.xpay.common.enums.partner.WithdrawStatus;
import com.net.xpay.common.manager.partner.PartnerWithdrawRecordManager;
import com.net.xpay.common.model.search.PartnerWithdrawRecordSearchModel;
import com.net.xpay.core.utils.JxlsUtils;
import com.net.xpay.partner.secutiry.RequestUser;
import com.net.xpay.partner.vo.PartnerWithdrawStatVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *

 * 合伙人提现记录
 */
@Slf4j
@RestController
@RequestMapping("/partner/partner-withdraw-record")
@Api(tags = "运营/合伙人提现记录", description = "运营 合伙人提现记录 net")
public class PartnerWithdrawRecordController {

    @Autowired
    private PartnerWithdrawRecordManager partnerWithdrawRecordManager;

    @ApiOperation("搜索合伙人提现记录")
    @PostMapping("/search")
    @ResponseBody
    public ResultPagedList<PartnerWithdrawRecord> searchPartnerWithdrawRecord(@ApiIgnore @RequestUser Partner partner, @RequestBody PartnerWithdrawRecordSearchModel searchModel) {
        searchModel.setPartnerId(partner.getId());
        //只查已打款的
        searchModel.setStatus(WithdrawStatus.PAYED);
        if (searchModel.getDay() != null) {
            String day = searchModel.getDay() + " 00:00:00";
            LocalDateTime yearMonth = LocalDateUtil.parseStringToDateTime(day);
            searchModel.setMinEndTime(LocalDateUtil.getMonthStartDay(yearMonth));
            searchModel.setMaxEndTime(LocalDateUtil.getMonthStartDay(yearMonth.plusMonths(1)));
        }
        List<PartnerWithdrawRecord> records = partnerWithdrawRecordManager.search(searchModel);
        long count = partnerWithdrawRecordManager.searchCount(searchModel);
        return new ResultPagedList<>(records, count, searchModel);
    }

    @ApiOperation("按月份统计提现金额")
    @PostMapping("/sum")
    @ResponseBody
    public ResultData<PartnerWithdrawStatVo> sumPartnerWithdrawStat(@ApiIgnore @RequestUser Partner partner,@RequestBody PartnerWithdrawRecordSearchModel  searchModel) {
        searchModel.setPartnerId(partner.getId());
        //只查已打款的
        searchModel.setStatus(WithdrawStatus.PAYED);
        if (searchModel.getDay() != null) {
            String day = searchModel.getDay() + " 00:00:00";
            LocalDateTime yearMonth = LocalDateUtil.parseStringToDateTime(day);
            searchModel.setMinEndTime(LocalDateUtil.getMonthStartDay(yearMonth));
            searchModel.setMaxEndTime(LocalDateUtil.getMonthStartDay(yearMonth.plusMonths(1)));
        }
        Long amount = partnerWithdrawRecordManager.sumPartnerWithdrawRecordStat(searchModel);
        PartnerWithdrawStatVo vo = new PartnerWithdrawStatVo();
        vo.setPartnerWithdrawAmount(amount);
        return new ResultData<>(vo);
    }

    /**
     * 提现记录导出
     */
    @ApiOperation("提现记录导出")
    @GetMapping("/export")
    public ResultData<Boolean> exportAccountLog(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, @ApiIgnore @RequestUser Partner partner, String searchModelJson) {
        Preconditions.checkArgument(searchModelJson != null);

        PartnerWithdrawRecordSearchModel searchModel = SerializationUtil.str2Object(searchModelJson, PartnerWithdrawRecordSearchModel.class);
        searchModel.setStatus(WithdrawStatus.PAYED);
        if (searchModel.getDay() != null) {
            String day = searchModel.getDay() + " 00:00:00";
            LocalDateTime yearMonth = LocalDateUtil.parseStringToDateTime(day);
            searchModel.setMinEndTime(LocalDateUtil.getMonthStartDay(yearMonth));
            searchModel.setMaxEndTime(LocalDateUtil.getMonthStartDay(yearMonth.plusMonths(1)));
        }
        searchModel.setPartnerId(partner.getId());
        List<PartnerWithdrawRecord> partnerWithdrawRecordList = partnerWithdrawRecordManager.list(searchModel);

        // 定义一个Map，往里面放入要在模板中显示数据
        Map<String, Object> model = new HashMap<>();

        model.put("records", partnerWithdrawRecordList);

        String fileName = "提现记录.xlsx";
        String template = "/excel/tpl/提现记录.xls";

        InputStream is;
        try {
            //获取模板流
            is = getClass().getResourceAsStream(template);

            //火狐游览器中文文件名会有乱码,兼容火狐
            String agent = request.getHeader("USER-AGENT").toLowerCase();

            if (!Strings.isNullOrEmpty(agent) && (agent.contains("firefox") || agent.contains("safari"))) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            JxlsUtils.exportExcel(is, response.getOutputStream(), model);
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("export error", e);
        }
        return new ResultData<>();
    }


}
